package hmis.pos.Service.ServiceImpl;

import hmis.pos.Base.BaseService.Impl.BaseServiceImpl;
import hmis.pos.Common.Util.TurnoverAndReservationAmount;
import hmis.pos.Common.pojo.ApiResponse;
import hmis.pos.Common.vo.ReportForm.FinalRoomStatistics;
import hmis.pos.Common.vo.ReportForm.RoomStatistics;
import hmis.pos.Common.vo.SearchPrice.RoomPriceTotal;
import hmis.pos.Common.vo.SearchPrice.TypeAndDate;
import hmis.pos.Entity.RoomType;
import hmis.pos.Repository.RoomMessageRepository;
import hmis.pos.Repository.RoomPriceRepository;
import hmis.pos.Entity.RoomPrice;
import hmis.pos.Service.RoomPriceService;
import hmis.pos.Service.RoomTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class RoomPriceServiceImpl extends BaseServiceImpl<RoomPrice,RoomPriceRepository> implements RoomPriceService{

    @Autowired
    private RoomPriceRepository roomPriceRepository;

    @Autowired
    private RoomTypeService roomTypeService;

    @Autowired
    private RoomMessageRepository roomMessageRepository;

    @Override
    public List<RoomPrice> findByType(String type) {
        return roomPriceRepository.findByType(type);
    }

    @Override
    public List<RoomPrice> findByDate(Date date) {
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE,1); //把日期往后增加一天,整数  往后推,负数往前移动
        Date date2 = calendar.getTime(); //这个时间就是日期往后推一天的结果
        return roomPriceRepository.findByDate(date);
    }

    @Override
    public List<RoomPrice> findByTypeAndDate2(TypeAndDate typeAndDate) {
        return roomPriceRepository.findByTypeAndDate(typeAndDate.getType(),typeAndDate.getDate());
    }

    @Override
    public List<RoomPriceTotal> findByTypeAndDate(TypeAndDate typeAndDate) {
        List<RoomPriceTotal> roomPriceTotalList = new ArrayList<>();

        Date in_time = typeAndDate.getIn_time();
        Date out_time = typeAndDate.getOut_time();

        List<RoomType> roomTypeList = new ArrayList<>();

        //判断是否输入房间类型
        if(typeAndDate.getType().equals("")){
            roomTypeList = roomTypeService.findAll();
        }else{
            roomTypeList.add(roomTypeService.findByType(typeAndDate.getType()));
        }

        for(RoomType roomType:roomTypeList){
            String type = roomType.getType();
            int minSurplus = 0;//最小可预订数
            double subtotal = 0;//小计金额
            RoomPriceTotal roomPriceTotal = new RoomPriceTotal();

            List<RoomPrice> roomPriceList = roomPriceRepository.findByTypeAndDateBetween(type,in_time,out_time);

            for(int i=0;i<roomPriceList.size();i++){
                RoomPrice roomPrice = roomPriceList.get(i);
                if(i==0)minSurplus = roomPrice.getSurplus();
                    if(minSurplus>roomPrice.getSurplus()){
                        minSurplus = roomPrice.getSurplus();//寻找最小可预订数
                    }
                    subtotal = subtotal + roomPrice.getPrice();//计算金额
            }
            if(roomPriceList.size()!=0) {
                roomPriceTotal.setMinSurplus(minSurplus);
                roomPriceTotal.setSubtotal(subtotal);
                roomPriceTotal.setRoomPriceList(roomPriceList);
                roomPriceTotal.setRoomType(roomType);
                roomPriceTotalList.add(roomPriceTotal);
            }
         }

         return roomPriceTotalList;
    }

    @Override
    public ApiResponse<RoomPrice> setDayPrice(RoomPrice roomPrice) throws ParseException {
        RoomPrice newRoomPrice = new RoomPrice();

        //获取今天日期
        Date today = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        today = sdf.parse(sdf.format(today));

        //今天日期与修改价格日期比较
        if(!roomPrice.getDate().after(today))return new ApiResponse<>(0,"当天及之前的价格不能修改!");

        //价格小于0
        if(roomPrice.getPrice()<=0)return new ApiResponse<>(0,"价格小于0 !");

        //查询数据库是否有该条价格记录
        List<RoomPrice> roomPriceList = roomPriceRepository.findByTypeAndDate(roomPrice.getType(),roomPrice.getDate());

        //判断该天价格是否已存在，已设置为更新价格，未设置为新添价格
        if(roomPriceList.size()>=1){
            roomPrice.setId(roomPriceList.get(0).getId());
            roomPrice.setSurplus(roomPriceList.get(0).getSurplus());
            roomPrice.setReservationcount(roomPriceList.get(0).getReservationcount());
            newRoomPrice = this.update(roomPrice);
            return new ApiResponse<>(1,"更新价格成功!",newRoomPrice);
        }
        else{
            roomPrice.setSurplus(roomMessageRepository.countByType(roomPrice.getType()));
            roomPrice.setReservationcount(0);
            newRoomPrice = roomPriceRepository.save(roomPrice);
            return new ApiResponse<>(1,"更新价格成功!",newRoomPrice);
        }

    }

    @Override
    public ApiResponse<RoomPrice> setMonthPrice(RoomPrice roomPrice) throws ParseException {
        List<RoomPrice> roomPriceList = new ArrayList<>();

        //获取今天的月份
        Date today = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-DD");
        today = sdf.parse(sdf.format(today));

        Calendar calendar = new GregorianCalendar();
        calendar.setTime(today);
        calendar.add(calendar.MONTH,-1); //把日期往后增加一月,整数  往后推,负数往前移动
        Date date2 = calendar.getTime(); //这个时间就是日期往后推一天的结果

        roomPrice.setDate(sdf.parse(sdf.format(roomPrice.getDate())));

        //今天月份与修改价格月份比较
        if(!roomPrice.getDate().after(date2))return new ApiResponse<>(0,"当月之前的价格不能修改!");

        //价格小于0
        if(roomPrice.getPrice()<=0)return new ApiResponse<>(0,"价格小于0 !");

        //循环月份的每一天
        calendar.setTime(roomPrice.getDate());
        int firstDay = calendar.getActualMinimum(Calendar.DAY_OF_MONTH);
        int lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        calendar.set(Calendar.DAY_OF_MONTH,firstDay);
        for(int i=1;i<=lastDay;i++){
            Date date = (sdf2.parse(sdf2.format(calendar.getTime())));
            RoomPrice roomPrice1 = new RoomPrice();
            roomPrice1.setDate(date);
            roomPrice1.setType(roomPrice.getType());
            roomPrice1.setPrice(roomPrice.getPrice());


            //设置每天价格
            ApiResponse<RoomPrice> roomPriceApiResponse = setDayPrice(roomPrice1);
            RoomPrice newRoomPrice = roomPriceApiResponse.getObj();
            if(roomPriceApiResponse.getEvent()==1)roomPriceList.add(newRoomPrice);
            calendar.add(calendar.DATE,1);
        }

        return new ApiResponse<>(1,"设置月价格成功,具体价格可到具体日期修改!",roomPriceList);
    }

    @Override
    public List<RoomPrice> findByMonth(Date date) {
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);

        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH)+1;
        return roomPriceRepository.findByMonth(year,month);
    }

    @Override
    public FinalRoomStatistics getYearData(int thisYear) {

        List<List<RoomStatistics>> turnover= new ArrayList<>();                //营业额

        List<List<RoomStatistics>> reservationAmount= new ArrayList<>();       //各种房型预订次数

        //获取房间类型
        List<RoomType> roomTypeList = roomTypeService.findAll();

        //获取五年内的年份
        List<Integer> years = new ArrayList<>();
        for(int i=-4;i<=0;i++){
            int year = thisYear + i;
            years.add(year);
        }

        for(int thatYear : years){
            List<RoomStatistics> turnoverList = new ArrayList<>();
            turnoverList.add(new RoomStatistics("state",thatYear));

            List<RoomStatistics> reservationAmountList = new ArrayList<>();
            reservationAmountList.add(new RoomStatistics("state",thatYear));

            //获取那一年的数据
            List<RoomPrice> roomPriceList = roomPriceRepository.findByYear(thatYear);

            //计算房型的总金额,各种房型预订次数
            for(RoomType roomType : roomTypeList){
                double totalValue = 0;
                int totalReservationAmount = 0;
                for(RoomPrice roomPrice : roomPriceList){
                    if(roomType.getType().equals(roomPrice.getType())){
                        //该房型的总营业额等于该房型的预订数量*价格
                        totalValue += roomPrice.getReservationcount()*roomPrice.getPrice();

                        totalReservationAmount += roomPrice.getReservationcount();
                    }
                }

                turnoverList.add(new RoomStatistics(roomType.getType(),totalValue));

                reservationAmountList.add(new RoomStatistics(roomType.getType(),totalReservationAmount));

            }

            turnover.add(turnoverList);
            reservationAmount.add(reservationAmountList);
        }

        return new FinalRoomStatistics(turnover,reservationAmount);
    }

    @Override
    public FinalRoomStatistics getMonthData(int thisYear){
        List<List<RoomStatistics>> turnover= new ArrayList<>();                //营业额

        List<List<RoomStatistics>> reservationAmount= new ArrayList<>();       //各种房型预订次数

        //获取房间类型
        List<RoomType> roomTypeList = roomTypeService.findAll();

        //建立月份数组进行循环
        List<Integer> months = new ArrayList<>();
        for(int i=1;i<=12;i++)
            months.add(i);

        for(Integer month : months) {

            //获取那一年特定月的数据
            List<RoomPrice> roomPriceList = roomPriceRepository.findByMonth(thisYear,month);

            List<RoomStatistics> turnoverList = new ArrayList<>();
            turnoverList.add(new RoomStatistics("state", month));

            List<RoomStatistics> reservationAmountList = new ArrayList<>();
            reservationAmountList.add(new RoomStatistics("state", month));

            //计算房型的总金额,各种房型预订次数
            for(RoomType roomType : roomTypeList){
                double totalValue = 0;
                int totalReservationAmount = 0;
                for(RoomPrice roomPrice : roomPriceList){
                    if(roomType.getType().equals(roomPrice.getType())){
                        //该房型的总营业额等于该房型的预订数量*价格
                        totalValue += roomPrice.getReservationcount()*roomPrice.getPrice();

                        totalReservationAmount += roomPrice.getReservationcount();
                    }
                }

                turnoverList.add(new RoomStatistics(roomType.getType(),totalValue));

                reservationAmountList.add(new RoomStatistics(roomType.getType(),totalReservationAmount));

            }

            turnover.add(turnoverList);
            reservationAmount.add(reservationAmountList);
        }

        return new FinalRoomStatistics(turnover,reservationAmount);
    }

    @Override
    public FinalRoomStatistics getSeasonData(int thisYear) {

        //获取月季报表数据
        FinalRoomStatistics finalRoomStatistics = getMonthData(thisYear);
        List<List<RoomStatistics>> turnover = finalRoomStatistics.getTurnover();
        List<List<RoomStatistics>> reservationAmount = finalRoomStatistics.getReservationAmount();

        //定义季度报表的营业额数据和预订天数数据
        List<List<RoomStatistics>> seasonTurnover = TurnoverAndReservationAmount.monthToSeason(turnover);
        List<List<RoomStatistics>> seasonReservationAmount = TurnoverAndReservationAmount.monthToSeason(reservationAmount);

        return new FinalRoomStatistics(seasonTurnover,seasonReservationAmount);

    }


}
